import 'dart:ui';
import 'package:flutter/animation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart' as svg;
import 'package:flutter_svg/svg.dart';
import 'package:hixing_app/assets/r_img.dart';
import 'package:hixing_app/views/test_view/test_matrix4/transform_vertex_model.dart';
import 'package:vector_math/vector_math_64.dart' as vector;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;
import 'package:get/get.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class NewTestMatrix4 extends StatefulWidget {
  @override
  _NewTestMatrix4State createState() => _NewTestMatrix4State();
}

class _NewTestMatrix4State extends State<NewTestMatrix4> {
  List<RectInfoModel> rectList = [];
  CanvasEventType? eventType;

  //transformVertex  存储大矩形变换后的四个顶点
  // TransformVertexModel? transformVertex;

  // 平移
  double dx = 100;
  double dy = 100;

  // 缩放比例，用来计算宽高比例的
  double wProportion = 1;
  double hProportion = 1;

  // 缩放后，把缩放后的矩形的中心点传入
  Offset imgRectCenter = Offset(0, 0);

  // 平移
  // double scaleDx = 0;
  // double scaleDy = 0;

  // 触摸点dx跟dy坐标跟起始dx dy修正
  double odx = 0;
  double ody = 0;

  Offset rotateTopleft = Offset(100, 100);

  double scaleOdx = 0;
  double scaleOdy = 0;

  bool isLock = true;

  // 绘制的企鹅 svg
  PictureInfo? imgSvgPicture;

  // 缩放
  double scaleX = 1;
  double scaleY = 1;

  // 缩放
  double? lockScaleX;

  double? lockScaleY;

  // 缩放的rect，
  Rect? scaleRenderRect;

  //svg  偏移量 ,用来计算触摸缩放的时候 点一下会放大的bug
  double correctSvgDx = 0;
  double correctSvgDy = 0;

  Size imgSize = Size(100, 100);
  Size iconSize = Size(30, 30);

  // 旋转
  double rotationAngle = 0.0;
  Offset initialPosition = Offset(0, 0);

  // 缩放前的图片尺寸
  double initScaleW = 0;
  double initScaleH = 0;

  Future<void> loadImg() async {
    var pgSvg = await rootBundle.loadString(ImgR.imgBgPguinSVG);
    final svg.PictureInfo pictureInfo1 = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          pgSvg,
        ),
        null);
    setState(() {
      imgSvgPicture = pictureInfo1;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadImg();
    // 初始化矩形中心点
    imgRectCenter = Offset(imgSize.width / 2, imgSize.height / 2);
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  void updateTopleft(Offset topLeft) {
    print("保存的左上角顶点${topLeft}");
    rotateTopleft = topLeft;
  }

  tapImage() {
    //计算当前触摸的点到img原点的距离，对齐偏移量
    odx = initialPosition.dx - dx;
    ody = initialPosition.dy - dy;
  }

  tapScale() {
    //计算当前触摸的点到scale icon原点的距离，对齐偏移量
    odx = initialPosition.dx - dx - (imgSize.width * scaleX);
    ody = initialPosition.dy - dy - (imgSize.height * scaleY);
    print("点击缩放偏移量：${odx},$ody");
    // print("缩放后的尺寸x: $initScaleW,Y: $initScaleW");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text('模板'),
      // ),
      body: Stack(
        children: [
          Listener(
            onPointerDown: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              initialPosition = globalPosition;

              for (var element in rectList) {
                if (element.path != null) {
                  if (element.path!.contains(globalPosition)) {
                    eventType = element.type;
                    print("element event ：${element.type}");
                    if (eventType == CanvasEventType.image) {
                      tapImage();
                    } else if (eventType == CanvasEventType.scale) {
                      tapScale();
                    } else if (eventType == CanvasEventType.lock) {
                      isLock = !isLock;

                      if (isLock) {
                        imgSize = Size((imgSize.width * scaleX),
                            (imgSize.height * scaleY));
                        scaleX = 1;
                        scaleY = 1;
                      }
                      // else {
                      //   lockScaleX = null;
                      //   lockScaleY = null;
                      // }

                      setState(() {});
                    }
                    break;
                  }
                }
              }
            },
            onPointerUp: (_) {
              if (eventType == CanvasEventType.scale) {
                // 旋转后 用缩放，原点会变化，所以这里得把原点重置一下

                // dx = transformVertex!.topLeft.dx;
                // dy = transformVertex!.topLeft.dy;
                // imgRectCenter = Offset(
                //     transformVertex!.topLeft.dx +
                //         ((imgSize.width * scaleX) / 2),
                //     transformVertex!.topLeft.dy +
                //         ((imgSize.height * scaleY) / 2));
                // print("当前的rect 中心点：${imgRectCenter}");
                // setState(() {});
                // imgSize = Size(imgSize.width * scaleX, imgSize.height * scaleY);
                // scaleX = 1;
                // scaleY = 1;
              }
              eventType = null;
            },
            onPointerMove: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              final newPosition = details.localPosition;
              final delta = newPosition - initialPosition;

              if (eventType == CanvasEventType.image) {
                // 平移元素操作
                setState(() {
                  dx = globalPosition.dx - odx;
                  dy = globalPosition.dy - ody;
                });
              } else if (eventType == CanvasEventType.scale) {
                Rect _rect;
                _rect = Rect.fromLTRB(
                    dx, dy, globalPosition.dx - odx, globalPosition.dy - ody);
                scaleX = _rect.width / imgSize.width;
                scaleY = _rect.height / imgSize.height;
                if (isLock) {
                  double computedScale = (scaleX + scaleY) / 2;
                  scaleX = computedScale;
                  scaleY = computedScale;
                }

                setState(() {});
              } else if (eventType == CanvasEventType.rotate) {
                // 求出当前坐标的方位角
                final angle = math.atan2(delta.dy, delta.dx);

                // final rotationFactor = 0.01;
                // final angle = math.atan2(delta.dy, delta.dx) * rotationFactor;

                if (initialPosition != null) {
                  setState(() {
                    rotationAngle = angle;
                  });
                }
              }
            },
            child: CustomPaint(
              size: Size.infinite,
              painter: MyCustomPainter(
                  rotationAngle: rotationAngle,
                  imgRectCenter: imgRectCenter,
                  imgSvgPicture: imgSvgPicture,
                  eventType: eventType,
                  rotateTopleft: rotateTopleft,
                  updateTopleft: updateTopleft,
                  // transformVertex: transformVertex,
                  isLock: isLock,
                  // lockScaleX: lockScaleX,
                  // lockScaleY: lockScaleY,
                  iconSize: iconSize,
                  scaleX: scaleX,
                  scaleY: scaleY,
                  imgSize: imgSize,
                  rectList: rectList,
                  wProportion: wProportion,
                  hProportion: hProportion,
                  dx: dx,
                  dy: dy),
            ),
          ),
          Positioned(
              top: 30,
              left: 30,
              child: Container(
                decoration: BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.circular(40)),
                child: IconButton(
                  onPressed: () {
                    Get.back();
                  },
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.yellowAccent,
                    size: 30,
                  ),
                ),
              )),
          // Positioned(
          //   top: 30,
          //   left: 130,
          //   child: Container(
          //     decoration: BoxDecoration(
          //         color: Colors.black26,
          //         borderRadius: BorderRadius.circular(40)),
          //     child: Text("${isLock ? "锁定" : "不锁定"}"),
          //   ),
          // )
        ],
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter(
      {this.rectList = const [],
      required this.dx,
      required this.dy,
      required this.scaleX,
      required this.scaleY,
      // required this.lockScaleX,
      // required this.lockScaleY,
      required this.imgSize,
      required this.isLock,
      required this.iconSize,
      required this.wProportion,
      required this.hProportion,
      required this.imgRectCenter,
      required this.imgSvgPicture,
      this.eventType,
      required this.rotateTopleft,
      required this.updateTopleft,
      // this.transformVertex,
      required this.rotationAngle});

  List<RectInfoModel> rectList;

  late TransformVertexModel transformVertex;

  final double dx;
  final double dy;
  final double rotationAngle;
  final bool isLock;
  final double scaleX;
  final double scaleY;
  final CanvasEventType? eventType;
  Offset rotateTopleft;

  // 上一次缩放后的矩形中心点传进来，在旋转的时候使用
  Offset imgRectCenter;
  Function(Offset) updateTopleft;

  // final double lockScaleX;
  // final double lockScaleY;
  final Size imgSize;
  final Size iconSize;
  final double dz = 1;
  final svg.PictureInfo? imgSvgPicture;

  final double hProportion;

  final double wProportion;

  // 定义缩放变量
  // final double scaleX = 1;
  // final double scaleY = 1;
  final double scaleZ = 1;

  @override
  void paint(Canvas canvas, Size size) {
    rectList.clear();

    // TODO: implement paint
    Paint _paint = Paint();
    CanvasUtils.drawGrid(canvas, _paint, size);
    CanvasUtils.drawCoor(canvas, _paint, size);
    if (imgSvgPicture != null) {
      Rect imgRect = Rect.fromLTWH(0, 0, imgSize.width, imgSize.height);

      // 计算图片中心点
      Offset scaledCenter = Offset(
        (imgSize.width * scaleX) / 2,
        (imgSize.height * scaleY) / 2,
      );

      Matrix4 scaleMatrix4 = Matrix4.identity()
        // ..translate(rotateTopleft.dx, rotateTopleft.dy)
        ..scale(scaleX, scaleY);
      // ..translate(-rotateTopleft.dx, -rotateTopleft.dy);

      Matrix4 rotateMatrix4 = Matrix4.identity();
      rotateMatrix4
        ..translate(scaledCenter.dx, scaledCenter.dy)
        ..rotateZ(rotationAngle)
        ..translate(-scaledCenter.dx, -scaledCenter.dy);

      Matrix4 translateMatrix4;

      late final Matrix4
          matrix; //= translateMatrix4 * rotateMatrix4 * scaleMatrix4;

      if (eventType == CanvasEventType.rotate) {
        // 先缩放，再旋转，然后平移 要按照这个顺序来执行以及写矩阵变换 执行顺序从右到左
        translateMatrix4 = Matrix4.identity()..translate(dx, dy);
        matrix = translateMatrix4 * rotateMatrix4 * scaleMatrix4;
      } else {
        translateMatrix4 = Matrix4.identity()..translate(dx, dy);
        matrix = translateMatrix4 * rotateMatrix4 * scaleMatrix4;
      }

      canvas.save();
      if (eventType == CanvasEventType.scale) {
        print("当前使用的顶点${rotateTopleft}");

        canvas.transform(matrix.storage);
        // canvas.translate(-rotateTopleft.dx, rotateTopleft.dy);
        // 应用变换

        // canvas.translate(-rotateTopleft.dx, -rotateTopleft.dy);
      } else {
        canvas.transform(matrix.storage);
      }

      canvas.drawRect(
          imgRect,
          _paint
            ..color = Colors.red
            ..strokeWidth = 10);
      // 绘制企鹅 svg  尺寸是imgSize
      drawResizeSvg(
          canvas, imgSvgPicture!.picture, imgSize, imgSvgPicture!.size,
          color: null);

      canvas.restore();

      // 因为上面平移到矩形的中心绘制了，这里也要平移到矩形的中心
      // 获取大矩形 旋转后的顶点
      vector.Vector4 topLef = vector.Vector4(
          -imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
      vector.Vector4 topRight = vector.Vector4(
          imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;

      vector.Vector4 bottomRight = vector.Vector4(
          imgSize.width / 2, imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
      vector.Vector4 bottomLeft = vector.Vector4(
          -imgSize.width / 2, imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;

      vector.Vector4 topLeftPosition = matrix.transformed(topLef);
      vector.Vector4 topRightPosition = matrix.transformed(topRight);
      vector.Vector4 bottomRightPosition = matrix.transformed(bottomRight);
      vector.Vector4 bottomLeftPosition = matrix.transformed(bottomLeft);
      transformVertex = TransformVertexModel(
        topLeft: Offset(topLeftPosition.x, topLeftPosition.y),
        topRight: Offset(topRightPosition.x, topRightPosition.y),
        bottomRight: Offset(bottomRightPosition.x, bottomRightPosition.y),
        bottomLeft: Offset(bottomLeftPosition.x, bottomLeftPosition.y),
      );
      canvas.save();
      // 绘制操作框的矩形
      Path tapImgPath = Path()
        ..moveTo(
            transformVertex.topLeft.dx, transformVertex.topLeft.dy); // 移动到第一个顶点
      tapImgPath
        ..lineTo(transformVertex.topRight.dx, transformVertex.topRight.dy)
        ..lineTo(transformVertex.bottomRight.dx, transformVertex.bottomRight.dy)
        ..lineTo(transformVertex.bottomLeft.dx, transformVertex.bottomLeft.dy);
      tapImgPath.close(); // 封闭路径
      Offset tapImgCenter =
          Offset(imgSize.width * scaleX / 2, imgSize.height * scaleY / 2);
      tapImgPath = tapImgPath.shift(tapImgCenter + Offset(dx, dy));

      //保存旋转后的左上角顶点，下次缩放的时候，用这个顶点来固定缩放
      if (eventType == CanvasEventType.rotate) {
        updateTopleft(tapImgPath.getBounds().topLeft);
        // print("当前的矩形数据${tapImgPath.getBounds()}");
        // 保存左上角的顶点
      }

      // 绘制矩形
      _paint
        ..color = Colors.greenAccent
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.0;
      // canvas.translate(
      //     tapImgPath.getBounds().center.dx, tapImgPath.getBounds().center.dy);

      canvas.drawPath(tapImgPath, _paint);

      canvas.restore();
      //
      canvas.save();
      Path _scalePath = Path()
        ..moveTo(
          bottomRightPosition.x,
          bottomRightPosition.y,
        ); // 移动到第一个顶点
      _scalePath
        ..relativeLineTo(iconSize.width, 0)
        ..relativeLineTo(0, iconSize.height)
        ..relativeLineTo(-iconSize.width, 0);
      _scalePath.close(); // 封闭路径

      _scalePath = _scalePath.shift(Offset(
          dx + imgSize.width * scaleX / 2, dy + imgSize.height * scaleY / 2));
      // 绘制矩形
      _paint
        ..color = Colors.greenAccent
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.0;

      canvas.drawPath(_scalePath, _paint);

      rectList.add(RectInfoModel(
          rect: Rect.zero, path: _scalePath, type: CanvasEventType.scale));

      Path _rotatePath = Path()
        ..moveTo(
          topRightPosition.x,
          topRightPosition.y,
        ); // 移动到第一个顶点
      _rotatePath
        ..relativeLineTo(iconSize.width, 0)
        ..relativeLineTo(0, -iconSize.height)
        ..relativeLineTo(-iconSize.width, 0);
      _rotatePath.close(); // 封闭路径

      _rotatePath = _rotatePath.shift(Offset(
          dx + imgSize.width * scaleX / 2, dy + imgSize.height * scaleY / 2));
      // 绘制矩形
      _paint
        ..color = Colors.redAccent
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.0;
      canvas.drawPath(_rotatePath, _paint);
      rectList.add(RectInfoModel(
          rect: Rect.zero, path: _rotatePath, type: CanvasEventType.rotate));

      // Rect _scaleRect = Rect.fromLTWH(bottomRightPosition.x,
      //     bottomRightPosition.y, iconSize.width, iconSize.height);
      //
      // canvas.drawRect(_scaleRect, _paint..color = Colors.black);
      // rectList.add(RectInfoModel(rect: _scaleRect, type: CanvasEventType.scale));
      //
      // Rect _rotateRect = Rect.fromLTWH(
      //     imgSize.width, -iconSize.height, iconSize.width, iconSize.height);
      // Rect _rotateTapRect =
      //     Rect.fromLTWH(200.0, 200.0, iconSize.width, iconSize.height);
      // canvas.drawRect(_rotateRect, _paint..color = Colors.red);
      // canvas.drawRect(_rotateTapRect, _paint..color = Colors.pink);
      //
      // rectList
      //     .add(RectInfoModel(rect: _rotateTapRect, type: CanvasEventType.rotate));

      canvas.restore();
    }
  }

  drawImgActionBox(Canvas canvas, Paint paint) {
    Path imgBoxPath = Path()
      ..moveTo(
          transformVertex!.topLeft.dx, transformVertex.topLeft.dy); // 移动到第一个顶点
    imgBoxPath
      ..lineTo(transformVertex!.topRight.dx, transformVertex.topRight.dy)
      ..lineTo(transformVertex!.bottomRight.dx, transformVertex.bottomRight.dy)
      ..lineTo(transformVertex!.bottomLeft.dx, transformVertex.bottomLeft.dy);
    imgBoxPath.close(); // 封闭路径

// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
    imgBoxPath = imgBoxPath.shift(
        Offset(dx + (imgSize.width / 2), dy + (imgSize.height / 2)) +
            Offset(200, 0));
//     rotatePath = rotatePath.shift(_center);
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawPath(imgBoxPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: imgBoxPath, type: CanvasEventType.image));
  }

  drawDeleteIcon(Canvas canvas, Paint paint,
      {required Offset bottomLeftOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();

    Path _rectPath = Path()
      ..moveTo(-iconSize.width, iconSize.height); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + bottomLeftOffset.dx + (imgSize.width / 2),
    //     (dy + bottomLeftOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + bottomLeftOffset.dx + (imgSize.width / 2),
        (dy + bottomLeftOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.delete));
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.translate(-iconSize.width, 0);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawLockIcon(Canvas canvas, Paint paint, {required Offset topLeftOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();

    Path _rectPath = Path()..moveTo(-iconSize.width, 0); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + topLeftOffset.dx + (imgSize.width / 2),
    //     (dy + topLeftOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + topLeftOffset.dx + (imgSize.width / 2),
        (dy + topLeftOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);

    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.lock));

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);

    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.translate(-iconSize.width, -iconSize.height);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawScaleIcon(Canvas canvas, Paint paint,
      {required Offset bottomRightOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();

    Path _rectPath = Path()..moveTo(0, iconSize.height); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + bottomRightOffset.dx + (imgSize.width / 2),
    //     (dy + bottomRightOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + bottomRightOffset.dx + (imgSize.width / 2),
        (dy + bottomRightOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.scale));

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawRotateIcon(Canvas canvas, Paint paint, {required Offset topRightOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();

    Path _rectPath = Path()..moveTo(0, 0); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);

    Offset boxVertex = Offset(dx + topRightOffset.dx + (imgSize.width / 2),
        (dy + topRightOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);

    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.rotate));

    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    // canvas.translate(0, -iconSize.height);

    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    svgRect = svgRect.shift(Offset(0, -iconSize.height));
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

void drawVertexRect({
  scaleIconSize = const Size(30, 30),
  required Canvas canvas,
  required Paint paint,
  required double rotationAngle,
  CanvasEventType eventType = CanvasEventType.image,
  RotateVertexType vertexType = RotateVertexType.bottomRight,
  required List<RectInfoModel> rectList,
  // 对齐的顶点实际屏幕坐标
  required Offset originVertex,
}) {
  canvas.save();

  // 每次都以平移后的点为原点绘制
  // canvas.translate(dx, dy);

  /// 添加一个缩放的tap 使用旋转后的顶点+ 平移矩形中心旋转的偏移量
  double _scaleRectLeft = originVertex.dx;
  double _scaleRectTop = originVertex.dy;
  Rect scaleTapRect = Rect.fromLTRB(
      _scaleRectLeft, _scaleRectTop, _scaleRectLeft + 30, _scaleRectTop + 30);

  // 绘制矩形路径
  Size scaleIconSize = Size(30, 30);
  List<Offset> _scaleOffsetList =
      getRotatePoint(scaleIconSize, Offset.zero, rotationAngle);
  double _vertextX;
  double _vertextY;
  if (vertexType == RotateVertexType.bottomRight) {
    // 传入原始矩形是右下顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[0].dx;
    _vertextY = _scaleOffsetList[0].dy;
  } else if (vertexType == RotateVertexType.topRight) {
    // 传入原始矩形是右上顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[3].dx;
    _vertextY = _scaleOffsetList[3].dy;
  } else if (vertexType == RotateVertexType.topLeft) {
    _vertextX = _scaleOffsetList[2].dx;
    _vertextY = _scaleOffsetList[2].dy;
  } else {
    _vertextX = _scaleOffsetList[1].dx;
    _vertextY = _scaleOffsetList[1].dy;
  }
  // 计算原始矩形右下顶点跟操作按钮矩形的左上顶点, 两个顶点的偏移量，然后减去这个偏移量
  double _scaleIconOffsetX =
      originVertex.dx - (scaleTapRect.center.dx + _vertextX);
  double _scaleIconOffsetY =
      originVertex.dy - (scaleTapRect.center.dy + _vertextY);

  Path _scaleIconPath = Path()
    ..moveTo(_scaleOffsetList[0].dx, _scaleOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _scaleOffsetList.length; i++) {
    _scaleIconPath.lineTo(
        _scaleOffsetList[i].dx, _scaleOffsetList[i].dy); // 添加线段
  }
  _scaleIconPath.close(); // 封闭路径
  // 把偏移量加回去, 这样就可以对其顶点了
  _scaleIconPath = _scaleIconPath.shift(
      scaleTapRect.center + Offset(_scaleIconOffsetX, _scaleIconOffsetY));
  // 绘制矩形
  paint
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;

  // canvas.translate(50, 200);
  canvas.drawPath(_scaleIconPath, paint);

  rectList.add(
      RectInfoModel(rect: Rect.zero, path: _scaleIconPath, type: eventType));

  canvas.restore();
}

List<Offset> getRotatePoint(Size imgSize, Offset center, double rotationAngle) {
  // double rotationAngle = math.pi / 3; // 旋转角度，单位为弧度

  // 计算矩形的中心点坐标
  // Offset center = Offset(0.0, 0.0); // 假设矩形中心点在原点

  // 计算每个顶点相对于中心点的坐标
  double halfWidth = imgSize.width / 2;
  double halfHeight = imgSize.height / 2;
  List<Offset> vertices = [
    Offset(-halfWidth, -halfHeight), // 左上角顶点
    Offset(halfWidth, -halfHeight), // 右上角顶点
    Offset(halfWidth, halfHeight), // 右下角顶点
    Offset(-halfWidth, halfHeight), // 左下角顶点
  ];

  // 应用旋转矩阵来计算旋转后的坐标
  List<Offset> rotatedVertices = [];
  for (var vertex in vertices) {
    double rotatedX = vertex.dx * math.cos(rotationAngle) -
        vertex.dy * math.sin(rotationAngle);
    double rotatedY = vertex.dx * math.sin(rotationAngle) +
        vertex.dy * math.cos(rotationAngle);
    rotatedVertices.add(Offset(rotatedX, rotatedY));
  }

  return rotatedVertices;
}

/// 通过计算旋转的坐标渲染旋转后的矩形
computedRotatePoint(Canvas canvas, Paint paint, Rect boxRect, Size imgSize,
    double rotationAngle) {
  canvas.save();
  Offset _center = Offset(boxRect.width / 2, boxRect.height / 2);

  //使用平移的方式修正偏移量，这里的起始点事原点，0，0
  // canvas.translate(_center.dx, _center.dy);

  // print("中心点：$_center");
  List<Offset> _rotateOffsetList =
      getRotatePoint(imgSize, _center, rotationAngle);

  // 绘制矩形路径
  Path path = Path()
    ..moveTo(_rotateOffsetList[0].dx, _rotateOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _rotateOffsetList.length; i++) {
    path.lineTo(_rotateOffsetList[i].dx, _rotateOffsetList[i].dy); // 添加线段
  }
  path.close(); // 封闭路径
// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
  path = path.shift(_center);
  // 绘制矩形
  paint
    ..color = Colors.blue
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;
  canvas.drawPath(path, paint);

  canvas.restore();
}

void drawResizeSvg(
    Canvas canvas, Picture picture, Size iconSize, Size originSize,
    {Color? color = Colors.white}) {
  Paint _paint = Paint();
  if (color != null) {
    _paint..colorFilter = ColorFilter.mode(color, BlendMode.srcIn);
  }
  canvas.saveLayer(
    null,
    _paint,
  );
  // canvas.translate(-size.width / 2, 0);
  canvas.scale(
      iconSize.width / originSize.width, iconSize.height / originSize.height);

  // 先定位好点，然后绘制
  canvas.drawPicture(picture);
  canvas.restore();
}

enum RotateVertexType { topLeft, topRight, bottomRight, bottomLeft }
